/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.mi.client.channel;

import java.util.List;

import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.MiProxyPublisher;
import org.bmi.gwt.mi.shared.MiPublisher;
import org.bmi.gwt.mi.shared.MiTransaction;
import org.bmi.gwt.mi.shared.MiTransactionPublisher;
import org.bmi.gwt.mi.shared.callbacks.AttributeCallback;
import org.bmi.gwt.mi.shared.callbacks.BindCallback;
import org.bmi.gwt.mi.shared.communication.attribute.AttributeValue;
import org.bmi.gwt.mi.shared.communication.call.Call;
import org.bmi.gwt.mi.shared.exceptions.BindNotAllowedException;
import org.bmi.gwt.mi.shared.exceptions.InvalidCredentialsException;
import org.bmi.gwt.mi.shared.util.ProxyFactory;
import org.bmi.gwt.mi.shared.util.WrapperFactory;

/**
 * Implementation of a {@link Channel} class suitable for client side.
 * 
 * @author marco.tamburelli@gmail.com
 */
class ChannelClient extends Channel
{
	protected Connection connection;

	private boolean discardOnDisconnect;

	ChannelClient(String queueName, ProxyFactory proxyFactory, WrapperFactory wrapperFactory, Connection connection,
			boolean discardOnDisconnect)
	{
		super();

		super.queueExpression = queueName;
		super.proxyFactory = proxyFactory;
		super.wrapperFactory = wrapperFactory;

		this.connection = connection;

		this.discardOnDisconnect = discardOnDisconnect;
	}

	@Override
	protected MiPublisher provideMiPublisher(boolean transactional)
	{
		if (transactional)
			return new MiTransactionPublisher();
		else
			return new MiProxyPublisher()
			{
				@Override
				protected void publish(List<Call> calls)
				{
					ChannelClient.this.connection.publish(super.broadChannel.getExpression(), calls);
				}
			};
	}

	@Override
	public void bind(BindCallback callback)
	{
		if (super.bindAllowed)
		{
			if (super.bound) return;

			this.connection.listen(super.queueExpression, super.attributes, this.discardOnDisconnect, callback);
			super.attributes.clear();
		}
		else
			callback.onError(new BindNotAllowedException("Channel doesn't allow to bind to queue '"
					+ super.queueExpression + "'."));
	}

	/**
	 * Should be called after some error occurred while binding or manipulating
	 * attributes,
	 */
	void disableBind()
	{
		super.bindAllowed = false;
	}

	/**
	 * should be called when the channel has lost contact with the queue.
	 */
	void disconnect()
	{
		super.bound = false;
	}

	/**
	 * Should be called when the channel is connected to the queue.
	 */
	void connect()
	{
		super.bound = true;
	}

	@Override
	public void unbind(boolean discard)
	{
		if (super.bound)
		{
			super.bound = false;
			ChannelClient.this.connection.free(super.queueExpression, discard);
		}
	}

	@Override
	protected void onResponse(List<Call> calls) throws Exception
	{
		manageResponse(calls);
	}

	@Override
	public MiTransaction createTransaction()
	{
		return new MiTransaction(this)
		{
			@Override
			protected void publish(List<Call> calls)
			{
				ChannelClient.this.connection.publish(super.broadChannel.getExpression(), calls);
			}
		};
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AttributeValue<?>> void getAttribute(String key, AttributeCallback<T> callback)
	{
		if (super.bound)
			this.connection.getQueueAttribute(this.queueExpression, key, callback);
		else
			callback.onSuccess((T) super.attributes.get(key));
	}

	@Override
	public <T extends AttributeValue<?>> void setAttribute(String key, T value, AttributeCallback<T> callback)
	{
		if (super.bound)
			this.connection.setQueueAttribute(this.queueExpression, key, value, callback);
		else if (super.bindAllowed)
		{
			super.attributes.put(key, value);
			callback.onSuccess(value);
		}
		else
			callback.onError(new InvalidCredentialsException("Impossible to update attribute of queue '"
					+ super.queueExpression + "' because provided credentials don't allow such operation."));
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends AttributeValue<?>> void removeAttribute(String key, AttributeCallback<T> callback)
	{
		if (super.bound)
			this.connection.removeQueueAttribute(this.queueExpression, key, callback);
		else if (super.bindAllowed)
			callback.onSuccess((T) super.attributes.remove(key));
		else
			callback.onError(new InvalidCredentialsException("Impossible to update attribute of queue '"
					+ super.queueExpression + "' because provided credentials don't allow such operation."));
	}
}
